#include "client.h"

int getMsg(char* usrname, char* password){
    printf("usrname:");
    fflush(stdout);
    fgets(usrname,128,stdin);
    usrname[strcspn(usrname, "\n")] = '\0';
    printf("password:");
    fflush(stdout);
    fgets(password,128,stdin);
    password[strcspn(password, "\n")] = '\0';
    
    return 0;
}

int login(int netfd,char* usrname,char* password){
    train_t train;
    train.tag = USRNAME;
    train.length = strlen(usrname) + 1;
    memcpy(train.data,usrname,train.length);
    send(netfd,&train,sizeof(train),MSG_NOSIGNAL);

    char salt[30] = {0};
    recv(netfd,&train,sizeof(train),0);
    LOG_ERROR_CHECK(train.tag,LOGIN,"recv in login");
    memcpy(salt,train.data,train.length);

    char* encrypted_passworld = crypt(password,salt);

    train.tag = ENCRYPTED;
    train.length = strlen(encrypted_passworld) + 1;
    memcpy(train.data,encrypted_passworld,train.length);
    send(netfd,&train,sizeof(train),MSG_NOSIGNAL);

    recv(netfd,&train,sizeof(train),0);
    if(train.tag == FILEEND){
        return 0;
    }else{
        return -1;
    }
}
